<?php

namespace Home\Controller;

use Think\Controller;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Lib\Timer;

class WorkerManController
{

    protected $socket = 'websocket://192.168.0.114:2346';
    protected $processes = 1;
    protected $uidConnections = array();

    private $uid = [];

    public function chat()
    {
        if (!IS_CLI) {
            die("无法直接访问，请通过命令行启动");
        }
        $clients = [];

        $users = [];

        $worker = new \Workerman\Worker('websocket://192.168.0.114:2346');

        $this->count = 3;


        $worker->onConnect = function ($connection) {

            global $clients;
            //$ipp = $connection->getRemoteIp();
//            $chatLog = M('Chat')->where("userid=1 and chatid=2")->order('addtime asc')->limit(3)->select();
//            $chatData = M('Chat')->where('status = 0 and chatid = 2')->order("addtime asc")->select();
//
//            $data = array_merge($chatLog, $chatData);
//            $connection->send('msg', $data);
            // 每10秒执行一次
            $time_interval = 1800;
            $connect_time = time();
            // 给connection对象临时添加一个timer_id属性保存定时器id
            $connection->timer_id = Timer::add($time_interval, function () use ($connection, $connect_time) {
                $connection->close();
            });
        };

        $worker->onMessage = function ($connection, $data) {
            $arr = explode(',', $data);
            global $clients;

            if ($arr[0] == 'login') {
                $tradeInfo = M('Trade')->where(array(
                    'id' => $arr[2]
                ))->find();

                if ($arr[1] == $tradeInfo['userid']) {
                    $chatid = $tradeInfo['trade_id'];
                }

                if ($arr[1] == $tradeInfo['trade_id']) {
                    $chatid = $tradeInfo['userid'];
                }

                $chatLog = M('Chat')->where("status = 1 and userid=" . $arr[1]  . " and chatid = " . $chatid .' and trade_id=' .$arr[2])->order('addtime asc')->limit(3)->select();
                $chatData = M('Chat')->where('status = 0 and userid=' . $arr[1] . ' and chatid = ' . $chatid . ' and trade_id=' .$arr[2])->order("addtime asc")->select();

                $chatDatas = array_merge($chatLog, $chatData);

                foreach ($chatDatas as $k => $v) {
                    $chatDatas[$k]['symbol'] = 1;
                }

                $tradeChatLog = M('Chat')->where("status = 1 and userid=" . $chatid  . " and chatid = " . $arr[1] .' and trade_id=' .$arr[2])->order('addtime asc')->limit(3)->select();

                $tradeChatData = M('Chat')->where('status = 0 and userid=' . $chatid . ' and chatid = ' . $arr[1] . ' and trade_id=' .$arr[2])->order("addtime asc")->select();

                $tradeChatDatas = array_merge($tradeChatLog, $tradeChatData);

                foreach ($tradeChatDatas as $k => $v) {
                    $tradeChatDatas[$k]['symbol'] = 2;
                }

                $chatInfo = array_merge($chatDatas , $tradeChatDatas);

                $chatlogs = json_encode($chatInfo);

                $connection->send($chatlogs);

//                $connection->send('notice:success'); //验证成功消息
//
//                $connection->send('msg:welcome '); //普通消息
                if (!isset($connection->uid)) {
                    //没有验证的话把第一个包当作uid
                    $connection->uid = $arr[1];
                    /**
                     * 保存uid到connection的映射，这样科研方便的通过uid 查找connection
                     * 实现对特定uid推送数据
                     */
                    $this->uidConnections[$connection->uid] = $connection;
                    return;
                }
            }
            //$uid = $arr[1];
            if ($arr[0] == 'chat') {
                $tradeid = $arr[3];

                $msg = array();

                $tradeData = M('Trade')->where(array(
                    'id' => $tradeid
                ))->find();

                if ($arr[1] == $tradeData['userid']) {
                    $uid = $tradeData['trade_id'];

                    $msg['symbol'] = 1;
                }

                if ($arr[1] == $tradeData['trade_id']) {
                    $uid = $tradeData['userid'];

                    $msg['symbol'] = 2;
                }

                if ($arr[4] == '') {
                    $content = '';
                    $img = $arr[5];
                }else{
                    $content = $arr[4];
                    $img = '';
                }

                if (isset($this->uidConnections[$uid])) {
                    M('Chat')->add(array(
                        'userid' => $arr[1],
                        'chatid' => $uid,
                        'content' => $content,
                        'addtime' => time(),
                        'status' => 1,
                        'trade_id' => $arr[3],
                        'img' => $img
                    ));

                    $msg['userid'] = $arr[1];

                    $msg['msg'] = $arr[4];

                    //$ret = $this->sendMessageByUid($uid, $data);
                    $connection = $this->uidConnections[$uid];
                    //$connection->send($arr[4]);
                    $content = json_encode($msg);
                    $connection->send($content);

                } else {
                    M('Chat')->add(array(
                        'userid' => $arr[1],
                        'chatid' => $uid,
                        'content' => $content,
                        'addtime' => time(),
                        'status' => 0,
                        'trade_id' => $arr[3],
                        'img' => $img
                    ));
                }
            }
        };

        $worker->onClose = function ($connection) //客户端主动关闭
        {

            global $this;
            if (isset($connection->uid)) {
                //连接断开是删除映射
                unset($this->uidConnections[$connection->uid]);
            }
//            global $clients;
//            global $tradeid;
//            //删除客户端ip
//            unset($clients[$connection->getRemoteIp() . ':' . $connection->getRemotePort()]);
//            //客户端关闭
//            echo "connection closed\n";
        };
        // 运行worker
        Worker::runAll();
    }


    public function onWorkerStart($worker)
    {
        //开启一个内部断开，方便内部系统推送数据，Text协议格式，文本+换行符
        $inner_text_worder = new \Workerman\Worker('text://192.168.0.114 :5678');
        $inner_text_worder->onMessage = function ($connection, $buffer) {
            echo 'hhh';
            //$data数组格式，里面有uid，表示向那个uid的页面推送数据
            $data = json_decode($buffer, true);
            $uid = $data['uid'];
            //通过workerman向uid的页面推送数据
            $ret = $this->sendMessageByUid($uid, $buffer);
            //返回推送结果
            $connection->send($ret ? 'ok' : 'fail');
        };
        //执行监听
        $inner_text_worder->listen();
    }

    public function syncUsers()
    {
        global $clients;
        $users = 'users:' . json_encode(array_column($clients, 'userid', 'ip')); //准备要广播的数据
        foreach ($clients as $ip => $client) {
            $client['conn']->send($users);
        }
    }

    public function onWorkerReload($worker)
    {
        foreach ($worker->connections as $connection) {
            $connection->send('worker reloading');
        }
    }

    //向所有验证的用户推送数据
    function broadcast($message)
    {
        foreach ($this->uidConnections as $connection) {
            $connection->send($message);
        }
    }

    //针对uid推送数据
    function sendMessageByUid($uid, $message)
    {
        if (isset($this->uidConnections[$uid])) {
            $connection = $this->uidConnections[$uid];
            $connection->send($message);
            return true;
        }
        return false;

    }

    public function onClose($connection)
    {
        global $this;
        if (isset($connection->uid)) {
            //连接断开是删除映射
            unset($this->uidConnections[$connection->uid]);
        }
    }


    public function onMessage($connection, $data)
    {

        //判断当前客户端是否已经验证，即是否设置啦uid
        if (!isset($connection->uid)) {
            //没有验证的话把第一个包当作uid
            $connection->uid = $data;
            /**
             * 保存uid到connection的映射，这样科研方便的通过uid 查找connection
             * 实现对特定uid推送数据
             */
            $this->uidConnections[$connection->uid] = $connection;
            return;
        }
    }
}
    //用于保存客户端信息

//    public function index()
//    {
//        if (!IS_CLI) {
//            die("无法直接访问，请通过命令行启动");
//        }
//        $clients = [];
//        $worker = new \Workerman\Worker('websocket://127.0.0.1:2346');
//
//        $this->count = 3;
//        $worker->onConnect = function ($connection) {
//            // 每10秒执行一次
//            $time_interval = 1800;
//            $connect_time = time();
//            // 给connection对象临时添加一个timer_id属性保存定时器id
//            $connection->timer_id = Timer::add($time_interval, function () use ($connection, $connect_time) {
//                $connection->close();
//            });
//        };
////        $worker->onWorkerStart = function ($data) {
//
////        };
//        $worker->onMessage = function ($connection, $data) {
//
//            // 向客户端发送hello $data
//            //$connection->send('hello ' . $data);
//            // 当收到客户端发来的数据后
//            global $clients;
//            $tradeid = $data[5];
//            //验证客户端用户名在3-20个字符
//            if (preg_match('/^login:(\w{3,20})/i', $data, $result)) { //代表是客户端认证
//                $ip = $connection->getRemoteIp();
//                $port = $connection->getRemotePort();
//
//                if (!array_key_exists($ip . ':' . $port, $clients)) { //必须是之前没有注册过
//
//                    //存储新登录用户的数据
//                    $clients[$ip . ':' . $port] = ['ipp' => $ip . ':' . $port, 'name' => $result[1], 'conn' => $connection];
//                    //dump($clients);
//                    // 向客户端发送数据
//                    $connection->send('notice:success'); //验证成功消息
//                    $connection->send('msg:welcome ' . $result[1]); //普通消息
//                    echo $ip . ':' . $port . '==>' . $result[1] . '==>login' . PHP_EOL; //这是为了演示,控制台打印信息
//                    $this->syncUsers();
//                    //M('Trade')->where('id = ' . $data[3])->setField('order_status',1);
//                    M('Trade')->where('id = 1')->setField('order_status', 1);
//                    Timer::del($connection->auth_timer_id);
//                }
//            } elseif (preg_match('/^chat:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                //$msg = $msgset[3];
//                //dump($msg);
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    $clients[$ipp]['conn']->send('msg:' . $msg);
//                    M('Chat')->add(array(
//                        //'usrid' => userid(),
//                        //'chatid' => $chatid,
//                        //'order_id' => $orderid,
//                        'content' => $msg,
//                        'addtime' => time()
//                    ));
//                    echo $ipp . '==>' . $msg . PHP_EOL;
//                }
//            } elseif (preg_match('/^paymoney:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                $tradeid = $msgset[3];
//                //$msg = $msgset[3];
//                //dump($msg);
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    $clients[$ipp]['conn']->send('msg:' . $msg);
//                    M('Trade')->where('id = 1')->setField('order_status', 2);
//                    //M('Trade')->where('id = ' .$tradeid)->setField('order_status',2);
//                    echo $msgset[3];
//                }
//            } elseif (preg_match('/^wait:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                $tradeid = $msgset[3];
//                //$msg = $msgset[3];
//                //dump($msg);
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    $clients[$ipp]['conn']->send('msg:' . $msg);
//                    M('Trade')->where('id = 1')->setField('order_status', 3);
//                    //M('Trade')->where('id = ' .$tradeid)->setField('order_status',3);
//                    echo $msgset[3];
//                }
//            } elseif (preg_match('/^speak:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                $trade_id = $msgset[3];
//                $trade_num = $msgset[4];
//                $user_praise = $msgset[5];
//                $user_trust = $msgset[6];
//                //$tradeid = $msgset[3];
//                //$msg = $msgset[3];
//                //dump($msg);
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    $clients[$ipp]['conn']->send('msg:' . $msg);
//                    M('Trade')->where('id = 1')->setField('order_status', 4);
//                    //M('Trade')->where('id = ' .$trade_id)->setField('order_status',4);
//                    M('UserCredit')->add(array(
//                        'userid' => $trade_id,
//                        'trade_num' => $trade_id,
//                        'user_praise' => $user_praise,
//                        'user_trust' => $user_trust
//                    ));
//                    echo $msgset[3];
//                }
//            } elseif (preg_match('/^commit:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                $tradeid = $msgset[3];
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    $clients[$ipp]['conn']->send('msg:' . $msg);
//                    M('Trade')->where('id = 1')->setField('order_status', 5);
//                    //M('Trade')->where('id = ' .$tradeid)->setField('order_status',5);
//                    echo $msgset[5];
//                    $connection->close();
//                }
//            }
//        };
//
//        $worker->onClose = function ($connection) //客户端主动关闭
//        {
//            global $clients;
//            global $tradeid;
//            unset($clients[$connection->getRemoteIp() . ':' . $connection->getRemotePort()]);
//            //M('Trade')->where('id = '. $tradeid)->setField('order_status' , 0);
//            //客户端关闭
//            echo "connection closed\n";
//        };
//        // 运行worker
//        Worker::runAll();
//    }


//    public function ceshi()
//    {
//        if (!IS_CLI) {
//            die("无法直接访问，请通过命令行启动");
//        }
//        $clients = [];
//
//        $worker = new \Workerman\Worker('websocket://192.168.0.115:2346');
//
//        $this->count = 3;
//
//        $worker->onConnect = function ($connection) {
//
//            global $clients;
//            //$ipp = $connection->getRemoteIp();
////            $chatLog = M('Chat')->where("userid=1 and chatid=2")->order('addtime asc')->limit(3)->select();
////            $chatData = M('Chat')->where('status = 0 and chatid = 2')->order("addtime asc")->select();
////
////            $data = array_merge($chatLog, $chatData);
////            $connection->send('msg', $data);
//            // 每10秒执行一次
//            $time_interval = 1800;
//            $connect_time = time();
//            // 给connection对象临时添加一个timer_id属性保存定时器id
//            $connection->timer_id = Timer::add($time_interval, function () use ($connection, $connect_time) {
//                $connection->close();
//            });
//        };
//
//        $worker->onMessage = function ($connection, $data) {
//
//            echo $data;
//            global $clients;
//            $tradeid = $data[5];
//            //验证客户端用户名在3-20个字符
//            //dump($connection);
//            if (preg_match('/^login:(\w{3,20})/i', $data, $result)) { //代表是客户端认证
//
//                $ip = $connection->getRemoteIp();
//                $port = $connection->getRemotePort();
//
//                if (!array_key_exists($ip . ':' . $port, $clients)) { //必须是之前没有注册过
//
//                    //存储新登录用户的数据
//                    $clients[$ip . ':' . $port] = ['ipp' => $ip . ':' . $port, 'name' => $result[1], 'conn' => $connection];
//                    // 向客户端发送数据
//                    $connection->send('notice:success'); //验证成功消息
//                    $connection->send('msg:welcome ' . $result[1]); //普通消息
//                    echo $ip . ':' . $port . '==>' . $result[1] . '==>login' . PHP_EOL; //这是为了演示,控制台打印信息
//                    $this->syncUsers();
//                    Timer::del($connection->auth_timer_id);
//                }
//            } elseif (preg_match('/^chat:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    if ($clients[$ipp]['conn']->send('msg:' . $msg)) {
//                        M('Chat')->add(array(
//                            'userid' => 1,
//                            'chatid' => 2,
//                            'content' => $msg,
//                            'addtime' => time(),
//                            'status' => 1
//                        ));
//                        echo $ipp . '==>' . $msg . PHP_EOL;
//                    } else {
//                        M('Chat')->add(array(
//                            'userid' => 1,
//                            'chatid' => 2,
//                            'content' => $msg,
//                            'addtime' => time(),
//                            'status' => 0
//                        ));
//                    }
//                }
//            } elseif (preg_match('/^symbolbuyer:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $ipp = $msgset[1];
//                $msg = $msgset[2];
//                if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                    //就发送普通消息
//                    $clients[$ipp]['conn']->send('msg:' . $msg);
//                }
//            } elseif (preg_match('/^symbolseller:\<(.*?)\>:(.*?)/isU', $data, $msgset)) {
//                $order_status = M('Trade')->where("id = 1")->getField("order_status");
//                $ipp = $msgset[1];
//                if ($order_status == 2) {
//                    $ipp = $msgset[1];
//                    $msg = $msgset[2];
//                    if (array_key_exists($ipp, $clients)) { //如果有这个用户
//                        //就发送普通消息
//                        $clients[$ipp]['conn']->send('msg:' . $msg);
//                    }
//                } else {
//                    $msg = array(
//                        'type' => 0,
//                        'msg' => "买家没标记付款"
//                    );
//                    $clients[$ipp]['conn']->send('msg:' . json_encode($msg));
//                }
//
//            }
//        };
//
//        $worker->onClose = function ($connection) //客户端主动关闭
//        {
//            global $clients;
//            global $tradeid;
//            //删除客户端ip
//            //unset($clients[$connection->getRemoteIp() . ':' . $connection->getRemotePort()]);
//            //客户端关闭
//            echo "connection closed\n";
//        };
//        // 运行worker
//        Worker::runAll();
//    }


//    public function login()
//    {
//        if (!IS_CLI) {
//            die("无法直接访问，请通过命令行启动");
//        }
//        $clients = [];
//
//        $worker = new \Workerman\Worker('websocket://192.168.0.114:2346');
//
//        $this->count = 3;
//
//        $worker->onConnect = function ($connection) {
//
//            global $clients;
//            // 每10秒执行一次
//            $time_interval = 1800;
//            $connect_time = time();
//            // 给connection对象临时添加一个timer_id属性保存定时器id
//            $connection->timer_id = Timer::add($time_interval, function () use ($connection, $connect_time) {
//                $connection->close();
//            });
//        };


//    }

